define(['butterfly/view', 'iscroll', 'main/util', 'main/ModuleManager', 'main/ModuleManager-browser'],
	function(View, IScroll, Util, Manager, ManagerBrowser){

  return View.extend({

  	events: {
  		"click #moduleBtn": "goModuleManager",
  		"click .module-board li": "goModule"
  	},

    onShow: function(){
    	var _this = this;
      var username = this.checkLogin();
      if(!username) return;
			var is_cordova = (typeof cordova != "undefined")
    	var manager = this.manager = is_cordova ? new Manager() :new ManagerBrowser();
      manager.getPrivellege(username, function(privellege) {
        manager.privellege = privellege.priviliges;
      });
      this.boardScroll = new IScroll("#wrapper", {mouseWheel: true});
      var installedModules = Util.loadData('installedModules');
      this.initInstalledModules(installedModules);
    },

    initInstalledModules: function(modules) {
        var _this = this;
        render(modules);
        this.manager.getLocalModulesInfo(function(modules) {
          Util.saveData('installedModules', modules);
          render(modules);
        });
        function render(modules) {
            if(!modules || modules.length == 0) return;
            var html = this.$("#module-tmpl").html(); // 得到需要被编译模板
            var tmpl = _.template(html);
            _this.$(".module-board").html("");
            var appIcon = Util.loadData('appIcon');
            _.each(modules, function(module) {
                if(!module.identifier || !module.build) return;
                module.icon = appIcon && appIcon[module.identifier] || "default"
                _this.$(".module-board").append(tmpl(module)); // 追加每个元素到指定元素
            });

            setTimeout(function() {
                _this.boardScroll.refresh();
            }, 200);
        }
    },

    checkLogin: function() {
      var username = localStorage.getItem('username');
      if(!username) {
        window.butterfly.navigate('#main/login.html');
      } 
      return username;
    },

    goModuleManager: function() {
      if(!this.checkLogin()) return;
    	window.butterfly.navigate("#main/update.html")
    },

    goModule: function(e) {
    	var identifier = $(e.currentTarget).data('identifier');
    	window.butterfly.navigate("#" + identifier + "/" + "index.html");
    }

  });
});
